package com.zw.demo01.config;

import com.zw.demo01.handler.*;
import com.zw.demo01.service.impl.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.config.annotation.web.configurers.RememberMeConfigurer;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.util.Collection;

/**
 * @ClassName: SecurityConfig
 * @Description TODO
 * @Author: zzw
 * @Date: 2023/3/31 14:50
 * @Version 1.0.0
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//    @Autowired
//    private DataSource dataSource;
//    @Autowired
//    private PersistentTokenRepository persistentTokenRepository;
//    @Autowired
//    private LoginService loginService;





//    @Override
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
////        auth.inMemoryAuthentication()
////                .withUser("user").password(passwordEncoder().encode("user")).roles("user")
////                .and()
////                .withUser("admin").password(passwordEncoder().encode("admin")).roles("admin");
//    }

//    @Override
//    public void configure(WebSecurity web) throws Exception {
//        web.ignoring().antMatchers("/js/**","/css/**","/img/**");
//    }

//    @Override
//    protected void configure(HttpSecurity http) throws Exception {
//            http
//                .formLogin()
//                .loginPage("/login.html")
//                .loginProcessingUrl("/login")
//                .successHandler(new MySuccessHandler())
//                .failureHandler(new MyFailureHandler())
//            .and()
//            .authorizeRequests()
//                .antMatchers("/login.html").permitAll()
////                .antMatchers("/admin/**").hasRole("admin")
////                .antMatchers("/user/**").hasRole("user")
//                .anyRequest().authenticated()
//
////                    自定义access方法
////              .authorizeRequests()
////                    .anyRequest().access("@myAccessServiceImpl.hasPermission(request,authentication)")
//            .and()
//                .logout().logoutUrl("/logout").logoutSuccessHandler(new MyLogoutSuccessHandler()).permitAll()
//            .and()
//                .exceptionHandling().authenticationEntryPoint(new MyAuthenticationEntryPoint())
//                    .accessDeniedHandler(new MyAccessDeniedHandler());
//
//
////            记住我
//        http.rememberMe()
////                设置数据源
//                .tokenRepository(persistentTokenRepository)
////                设置参数
//                        .rememberMeParameter("remember-me")
////                设置过期时间
//                                .tokenValiditySeconds(60)
////                自定义登录逻辑
//                                        .userDetailsService(loginService);
//
//
//        http
//            .csrf().disable();
//    }





    //角色继承
//    @Bean
//   public RoleHierarchy roleHierarchy() {
//        RoleHierarchyImpl hierarchy = new RoleHierarchyImpl();
//        hierarchy.setHierarchy("ROLE_admin > ROLE_user");
//        return hierarchy;
//    }
//
//    //  数据库
//    @Bean
//   public PersistentTokenRepository persistentTokenRepository(){
//        JdbcTokenRepositoryImpl jdbcTokenRepository=new JdbcTokenRepositoryImpl();
////        设置数据源
//        jdbcTokenRepository.setDataSource(dataSource);
//
////        第一次启动需开启创建表格，后续需关闭
////        jdbcTokenRepository.setCreateTableOnStartup(true);
//        return jdbcTokenRepository;
//
//    }




    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

//spring security +oauth2
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin().permitAll()
                .and().authorizeRequests().antMatchers("/login/**","/oauth/**","/message/**").permitAll()
                .anyRequest().authenticated()
                .and().csrf().disable();
}
}
